package com.iwdnb.gkgz.common.utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.iwdnb.gkgz.common.model.dto.StockDayData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import static com.iwdnb.gkgz.common.utils.BigDecimalUtils.round;

@Slf4j
public class CandleDataBuilder {

    public static List<StockDayData> candleToDayData(String candleData) {
        if (StringUtils.isBlank(candleData)) {
            return null;
        }
        String[] str = candleData.split(",");
        List<StockDayData> stockDayDataList = new ArrayList<>();
        for (String s : str) {
            String[] array = s.split("_");
            StockDayData stockDayData = new StockDayData();
            stockDayData.setDate(array[0]);
            stockDayData.setOpenPrice(new BigDecimal(array[1]));
            stockDayData.setClosePrice(new BigDecimal(array[2]));
            stockDayData.setMaxPrice(new BigDecimal(array[3]));
            stockDayData.setMinPrice(new BigDecimal(array[4]));
            stockDayData.setTradeNum(new Integer(array[5]));
            if (array.length == 7) {
                stockDayData.setRate(new BigDecimal(array[6]));
            }
            stockDayDataList.add(stockDayData);
        }
        StockUtils.sortStockDayDataList(stockDayDataList);
        return stockDayDataList;
    }

    public static String dayDataToCandle(List<StockDayData> stockDayDataList) {
        if (CollectionUtils.isEmpty(stockDayDataList)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (StockDayData data : stockDayDataList) {
            sb.append(dayDataToCandle(data)).append(",");
        }
        return StringUtils.removeEnd(sb.toString(), ",");
    }

    public static String dayDataToCandle(StockDayData data) {
        return data.getDate()
            + "_" + round(data.getOpenPrice())
            + "_" + round(data.getClosePrice())
            + "_" + round(data.getMaxPrice())
            + "_" + round(data.getMinPrice())
            + "_" + data.getTradeNum()
            + "_" + data.getRate();
    }
}
